package org.example.socketdemos.filecopy;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * read：
 *      1、CPU从用户态切换到内核态
 *      2、系统调用：磁盘文件内容copy到内核缓冲区
 *      3、内核缓冲区copy内容到进程缓冲区
 *      4、CPU从内核态切换到用户态
 * write：
 *      1、进程缓冲区copy到socket缓冲区：CPU从用户态切换到内核态
 *      2、socket缓冲区copy到网卡
 *      3、CPU从内核态切换到用户态
 *  上述发生了：4次CPU切换，4次copy
 */
@Slf4j
public class FileClientSocket {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket();
            log.info("连接8080端口");
            socket.connect(new InetSocketAddress(8080));
            log.info("连接成功");

            OutputStream outputStream = socket.getOutputStream();

            File file = new File("d:/py3.8.yaml");
            FileInputStream fous = new FileInputStream(file);
            byte[] contens = new byte[4096];
            int length = -1;
            while ((length = fous.read(contens)) != -1) {
                outputStream.write(contens, 0, length);
                outputStream.flush();
            }

            // 关闭输出流并写一个结束标记
            socket.shutdownOutput();

            InputStream inputStream = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            byte[] serverContents = new byte[4096];
            while ((length = bis.read(serverContents)) != -1) {
                // 应该输出读到的字节数
                log.info(new String(serverContents));
            }

            Thread.sleep(Integer.MAX_VALUE);

        } catch (IOException|InterruptedException e) {
            log.error(e.getMessage());
        }
    }
}
